package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.mall.user.AddressOrderDto;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.remote.AddressApiClient;
import com.cskaoyan.order.remote.ProductApiClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理物流信息（商品寄送的地址）
 */
@Slf4j
@Component
public class LogisticalHandler extends AbstractTransHandler {

    @Autowired
    AddressApiClient addressApiClient;
    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        ServiceCallResponse<AddressOrderDto> serviceCallResponse = addressApiClient.queryAddressByAddressId(createOrderContext.getAddressId());
        AddressOrderDto callData = serviceCallResponse.getCallData();

        OrderShipping orderShipping = new OrderShipping();
        orderShipping.setReceiverName(callData.getUserName());
        orderShipping.setReceiverMobile(callData.getTel());
        orderShipping.setReceiverPhone(callData.getTel());
        orderShipping.setReceiverAddress(callData.getStreetName());
        orderShipping.setCreated(new Date());
        orderShipping.setUpdated(new Date());
        orderShipping.setOrderId(createOrderContext.getOrderId());
        try {
            orderShippingMapper.insertSelective(orderShipping);
        } catch (Exception e) {
            throw new BizException(OrderRetCode.SHIPPING_DB_SAVED_FAILED.getCode(),
                    OrderRetCode.SHIPPING_DB_SAVED_FAILED.getMessage()
            );
        }
        return true;
    }
}
